package com.wkbb.basic.service.impl;

import com.wkbb.basic.mapper.DeviceSerialMapper;
import com.wkbb.basic.mapper.DeviceTypeMapper;
import com.wkbb.basic.model.DeviceSerial;
import com.wkbb.basic.model.DeviceType;
import com.wkbb.basic.service.DeviceTypeService;
import com.wkbb.basic.vo.DeviceTypeManageVo;
import com.wkbb.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class DeviceTypeServiceImpl extends BaseServiceImpl<DeviceType> implements DeviceTypeService {

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;

    @Autowired
    private DeviceSerialMapper deviceSerialMapper;

    @Autowired
    public void setMapper(DeviceTypeMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public DeviceTypeManageVo getInfo(Long id) {
        return deviceTypeMapper.getDeviceTypeManageVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids, String deleteBy) {
        if (ids.isEmpty()) {
            return;
        }

        for (Long id : ids) {
            if (id == null || id == 0) {
                return;
            }

            //先删除串口
            deleteDeviceSerial(id);
            //后删除设备类型
            deleteDeviceType(id, deleteBy);
        }
    }

    private void deleteDeviceSerial(Long id) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("deviceTypeId", id);

        deviceSerialMapper.deleteByParams(params);
    }

    private void deleteDeviceType(Long id, String deleteBy) {
        DeviceType deviceType = new DeviceType();
        deviceType.setId(id);
        deviceType.setUpdateBy(deleteBy);
        deviceType.setStatus(false);
        deviceTypeMapper.update(deviceType);
    }


    /**
     * 检查学校是否有晨检机
     * @param params 学校ID
     * @return 晨检机数量
     */
    public int getMorningCheckFlag(Map<String,Object> params){
        return deviceTypeMapper.getMorningCheckFlag(params);
    }
}
